package com.itmei.threadpool.video;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;


/**
 * @Author itmei
 * @Date 2023/3/16 15:44
 * @description: 视频下载模拟
 * @Title: VideoService
 * @Package com.itmei.threadpool.video
 */
@Service
public class VideoService implements ApplicationRunner {
    @Resource
    private ThreadPoolTaskExecutor taskExecutor;
    private final Logger log = LoggerFactory.getLogger(VideoService.class);
    /**
     * 是否开启多线程
     */
    private boolean threadFlag = true;
    @Override
    public void run(ApplicationArguments args) throws Exception {
        init();
    }
    public void download(){
        try {
            //模拟睡眠10秒，比作下载视频所需要的时间
            log.info("线程{}开始下载",Thread.currentThread().getName());
            Thread.sleep(10*1000);
            log.info("线程{}下载完成",Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void init(){
        //模拟下载5个视频
        int videos = 5;
        long startTime = System.currentTimeMillis();
        log.info("》》》开始下载视频《《《");
        for (int i = 0; i < videos; i++) {
            if (threadFlag){
                taskExecutor.execute(() -> {
                    //线程任务
                    download();
                });
            }else {
                download();
            }
        }
        //需要等待子线程完成后再走主线程
        while (threadFlag){
            try {
                int activeCount = taskExecutor.getActiveCount();
                if (activeCount == 0) {
                    break;
                }
                //让主线程等待个1秒减少while的次数
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        long endTime = System.currentTimeMillis();
        log.info("总耗时：{} 秒!",(endTime-startTime)/1000);
    }
}
